import { ref, computed } from "vue";
import { defineStore } from "pinia";
import { authApi, authService } from "@/services/authService";
import { setFamilyTitle, resetDocumentTitle } from "@/utils/documentTitle";
import type { FamilyMemberResponse } from "@/types/auth";

export const useAuthStore = defineStore("auth", () => {
  // 状态
  const user = ref<FamilyMemberResponse | null>(null);
  const isLoading = ref(false);
  const error = ref<string | null>(null);

  // 计算属性
  const isAuthenticated = computed(() => !!user.value);
  const username = computed(() => user.value?.username || "");
  const fullName = computed(() => user.value?.full_name || "");
  const role = computed(() => user.value?.role || null);
  const isAdmin = computed(() => role.value === "admin");

  // 初始化认证状态
  async function initAuth() {
    try {
      isLoading.value = true;
      error.value = null;

      // 检查本地存储中是否有用户信息
      const savedUser = authService.getUser();
      if (savedUser && authService.getToken()) {
        // 验证 token 是否有效
        const userData = await authApi.verifyToken();
        user.value = userData;
      } else {
        // 清除无效的认证信息
        authService.clearAuth();
        user.value = null;

        // 设置默认标题
        resetDocumentTitle();
      }
    } catch (err) {
      console.error("初始化认证状态失败:", err);
      error.value = "认证状态初始化失败";
      authService.clearAuth();
      user.value = null;

      // 设置默认标题
      resetDocumentTitle();
      
      // 触发认证要求事件（仅在初始化失败时）
      if (authService.getToken()) {
        // 如果有token但验证失败，说明token过期
        const event = new CustomEvent("auth-required");
        window.dispatchEvent(event);
      }
    } finally {
      isLoading.value = false;
    }
  }

  // 登录
  async function login(
    username: string,
    password: string,
    rememberMe: boolean = false,
  ) {
    try {
      isLoading.value = true;
      error.value = null;

      const response = await authApi.login({ username, password });

      // 保存认证信息
      authService.saveAuth(response, rememberMe);
      user.value = response.family_member;

      // 更新浏览器标题为家庭名称
      setFamilyTitle(response.family_member?.family_name || undefined);

      return { success: true };
    } catch (err) {
      console.error("登录失败:", err);
      error.value = "登录失败，请检查用户名和密码";
      user.value = null;

      // 确保标题为默认值
      resetDocumentTitle();

      return { success: false, error: error.value };
    } finally {
      isLoading.value = false;
    }
  }

  // 登出
  async function logout() {
    try {
      isLoading.value = true;
      error.value = null;

      // 调用后端登出接口
      await authApi.logout();

      // 清除本地认证信息
      authService.clearAuth();
      user.value = null;

      // 恢复浏览器标题为默认值
      resetDocumentTitle();

      return { success: true };
    } catch (err) {
      console.error("登出失败:", err);
      error.value = "登出失败";

      // 即使后端登出失败，也要清除本地认证信息
      authService.clearAuth();
      user.value = null;

      // 恢复浏览器标题为默认值
      resetDocumentTitle();

      return { success: false, error: error.value };
    } finally {
      isLoading.value = false;
    }
  }

  // 清除错误
  function clearError() {
    error.value = null;
  }

  // 检查权限
  function hasRole(requiredRole: string): boolean {
    return role.value === requiredRole;
  }

  return {
    // 状态
    user,
    isLoading,
    error,

    // 计算属性
    isAuthenticated,
    username,
    fullName,
    role,
    isAdmin,

    // 方法
    initAuth,
    login,
    logout,
    clearError,
    hasRole,
  };
});
